/**
 * 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
 */
const $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678'
//不添加重复项
// Array.prototype.pushWithoutDuplicate = function () {
//   for (let i = 0; i < arguments.length; i++){
//     const arg = arguments[0]
//     if (this.indexOf(arg) === -1)
//       this.push(arg)
//   }
// }
/**
 * 生成指长度的随机数
 *
 * @param {*} ilen 默认6位
 * @returns
 */
export function randomWord (ilen) {
  let pwd = ''
  ilen = ilen || 6
  for (let i = 0; i < ilen; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * $chars.length))
  }
  return pwd
}
// 生成UUID 方法一
export function uuid()  {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,  (c)=> {
    let r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}
/**
 * 判断对象变量不是空的
 */
export function isDef (v) {
  return v !== undefined && v !== null
}

/**
 * 删除数组元素
 * @param {*} arr
 * @param {*} item
 * @returns
 */
export function removeArray (arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}
/**
 * 判断是否为正则对象（正则表达式类型）
 * @param {*} v
 * @returns
 */
export function isRegExp (v) {
  return Object.prototype.toString.call(v) === '[object RegExp]'
}
/**
 * 判断是否为JSON对象
 * @param {*} obj
 * @returns
 */
export function isJSON (obj) {
  try {
    return typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Object]'
  } catch (e) {
    console.error(e)
    return false
  }
}
export function isJSONObject(value) {
  return typeof value === 'object' && JSON.stringify(value) !== undefined
}
/**
 * 数据类型
 * @param {*} data
 * @returns
 */
export function checkType (data) {
  return Object.prototype.toString.call(data)
}

/**
 * 多级树转列表
 *
 * @param tree Tree JSON 数组
 * @param children 子节点字段
 */
export function treeToList (tree, children = 'children') {
  return tree.reduce((list, item) => {
    let childrenData = item[children]
    if (childrenData?.length > 0) {
      childrenData = treeToList(childrenData)
      list = list.concat(childrenData)
    }
    list.push(item)
    return list
  }, [])
}

/**
 * 检查是否为空的JSON
 * @param {JSON} obj
 * @returns
 */
export function isEmptyJSON (obj) {
  // json.hasOwnProperty('key') 判断key是否存在
  return Object.keys(obj).length > 0
}

/**
 * 清空JSON对象key的值
 * @param {JSON} obj
 */
export function cleanJsonData(obj) {
  //方法一:(无法清空)
  // Object.assign(obj, {})
  //方法二:
  console.dir(Object.keys(obj))
  Object.keys(obj).map(key=> {
    console.info('---->>>', key, '------'  , typeof (obj[key]))
    if (typeof (obj[key]) == 'object') {
      obj[key] = []
    } else if (typeof (obj[key]) == 'number') {
      obj[key] = null
    } else if (typeof (obj[key]) == 'string') {
      obj[key] = ''
    } else {
      obj[key] = undefined
    }
  })
  // // 方法三
  // const keys = Object.keys(obj)
  // keys.forEach(item => {
  //   delete obj[item]
  // })
}

/**
 * 清除非父节点的chilren 属性
 *
 * @param tree Tree JSON 数组
 * @param children 子节点字段
 */
export function TreeCleanEmptyNode(treeList, children = 'children') {
  //console.info('treeCleanEmptyNode....................', treeList)
  treeList.forEach(it => {
    let childrenData = it[children]
    if (childrenData?.length > 0) {
      TreeCleanEmptyNode(childrenData, children)
    } else {
      delete it[children]
    }
  })
}

/**
 * 查找上一级ID
 */
export function findParentById(arr,id){
  let parentId = '没有父元素',
    hasParentId = function loop(arr){
      return arr.some((item)=>{
        if(item.id === id){
          return true
        }else if(Array.isArray(item.children)){
          parentId = item.id
          return loop(item.children)
        }else{
          return false
        }
      })
    }(arr)
  return hasParentId ? parentId : '未找到对应父元素'
}

/**
 * 查找所有的级 
 * 
 */
export function findParentsById(arr,id){
  let parentIds = [],
    index = 0,
    hasParentId = function loop(arr, index){
      return arr.some((item)=>{
        if(item.id === id){
          parentIds = parentIds.slice(0, index)
          return true
        }else if(Array.isArray(item.children)){
          parentIds[index] = item.id
          return loop(item.children, index+1)
        }else{
          return false
        }
      })
    }(arr, index)
  return hasParentId ? parentIds : []
}
/** 
 * 递归查找目标节点 
 */  
export function findTarget(obj, targetId, targetChildren){  
  if(obj.id == targetId){  
    obj.children = targetChildren  
    return true  
  }else{  
    if(obj.children!=null){  
      for(let i=0; i<obj.children.length; i++){  
        let flag=findTarget(obj.children[i],targetId,targetChildren)  
        if(flag==true){  
          return true  
        }  
      }  
    }  
  }  
  return false  
}

/**
 * 节流函数
 * @param {*} fun 函数
 * @param {*} delay 时间
 * @returns 
 */
export function throttler(fun, delay) {
  let last, deferTimer
  return () => {
    let that = this,  _args = arguments, now = +new Date()
    if (last && now < last + delay) {
      clearTimeout(deferTimer)
      deferTimer = setTimeout(()=> {
        last = now
        fun.apply(that, _args)
      }, delay)
    }else {
      last = now
      fun.apply(that, _args)
    }
  }
}
/**
 * 检查元素是否是body元素的后代元素且非body元素本身
 * @param {*} node 
 * @returns 
 */
export function isInPage(node) {
  return (node === document.body) ?false : document.body.contains(node)
}